<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .success {
        background: rgb(232, 241, 217);
      }
      .error {
        background: rgb(243, 211, 211);
      }
    </style>
  </head>
  <body>
    <form name="form">
      <p>
        姓名 <input type="text" name="username" />
        <span id="username" style="display: none">用户名6-18个字符</span>
      </p>
      <p>
        邮箱 <input type="text" name="email" />
        <span id="email" style="display: none">邮箱格式错误</span>
      </p>
      <p>
        手机 <input type="text" name="phone" />
        <span id="phone" style="display: none">手机格式错误</span>
      </p>
      <p>
        <button type="button">提交</button>
      </p>
    </form>
    <script>
      /*
        表单验证
        1. 不为空验证
        oninput 实现输入验证
        1. 事件委托绑定事件
        2. 通过判断用户在哪个对象输入
        3. 验证用户输入
        封装重复的业务逻辑（函数封装）
        1. 输入（参数）
        2. 输出（返回值）
        */
      function valid(target, cb) {
        const name = e.target.name;
        const errMsg = document.getElementById(name);
        if (cb()) {
          errMsg.style.display = "";
          target.classList.remove("success");
          target.classList.add("error");
        } else {
          errMsg.style.display = "none";
          target.classList.remove("error");
          target.classList.add("success");
        }
      }
      document.oninput = function (e) {
        const target = e.target;
        const name = e.target.name;
        const errMsg = document.getElementById(name);
        // 验证用户名
        if (name === "username") {
          if (/^\w{2,18}$/.test(target.value) === false) {
            errMsg.style.display = "";
            target.classList.remove("success");
            target.classList.add("error");
          } else {
            errMsg.style.display = "none";
            target.classList.remove("error");
            target.classList.add("success");
          }
        }
        // 验证邮箱
        if (name === "email") {
          // jack@qq.com
          if (/^\w+@\w+\.\w+$/.test(target.value) === false) {
            errMsg.style.display = "";
            target.classList.remove("success");
            target.classList.add("error");
          } else {
            errMsg.style.display = "none";
            target.classList.remove("error");
            target.classList.add("success");
          }
        }
        // 手机验证
        if (name === "phone") {
          if (/^1[3-9]\d{9}$/.test(target.value) === false) {
            errMsg.style.display = "";
            target.classList.remove("success");
            target.classList.add("error");
          } else {
            errMsg.style.display = "none";
            target.classList.remove("error");
            target.classList.add("success");
          }
        }
      };
    </script>
  </body>
</html>
